using System;
using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.Base.Exceptions;
using Habanero.BO;
using Habanero.Faces.Base;
using Habanero.Faces.Win;

namespace FireStarterModeller.UI
{
    /// <summary>
    /// A control for selecting and adding a unique constriant for a particular <see cref="DMClass"/>
    /// </summary>
    public class DMUniqueConstraintSelectorControl : UserControlWin, IFormControl, IBOParentChildrenSelector
    {
        private DMClass _class;
        private IFormHabanero _uniqueConstraintPropertyForm;
        public IControlFactory ControlFactory { get; private set; }
        public IGridControl GridControl { get; private set; }

        public event EventHandler<BOEventArgs<DMUniqueConstraint>> UniqueConstraintSelected;

        public DMUniqueConstraintSelectorControl(IControlFactory controlFactory)
        {
            if (controlFactory == null)
                throw new HabaneroArgumentException
                    ("controlFactory", "Cannot create an 'DMUniqueConstraintSelectorControl' if the control factory is null");
            ControlFactory = controlFactory;
            GridControl = controlFactory.CreateEditableGridControl();

            IButtonGroupControl buttonGroupControl = GridControl.Buttons;
            buttonGroupControl["Save"].Visible = false;
            buttonGroupControl.AddButton("AddProperties", "Add Properties", AddProperties_ClickHandler );
            GridControl.Width = 270;
            this.GridControl.ConfirmDeletion = true;
            //This is done so that the grid is set up with the basic columns etc required for DMUniqueConstraint
            GridControl.BusinessObjectCollection = new BusinessObjectCollection<DMUniqueConstraint>();
            foreach (IDataGridViewColumn column in GridControl.Grid.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            BorderLayoutManager mainLayoutManager = controlFactory.CreateBorderLayoutManager(this);
            mainLayoutManager.AddControl(GridControl, BorderLayoutManager.Position.Centre);

            GridControl.BusinessObjectSelected += ((sender, e) =>
                {
                    try
                    {
                        EnableAddPropertiesButton();
                        FireUniqueConstraintSelected((DMUniqueConstraint) e.BusinessObject);
                    }
                    catch (Exception ex)
                    {
                        GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
                    }
                });
            this.Enabled = false;
        }

        private void AddProperties_ClickHandler(object sender, EventArgs e)
        {
            try
            {
                ShowUniqueContraintPropertySelectorForm();
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error ");
            }
        }

        private void ShowUniqueContraintPropertySelectorForm()
        {
            DMUniqueConstraint dmUniqueConstraint = this.SelectedUniqueConstraint;
            if (dmUniqueConstraint == null) return;
            _uniqueConstraintPropertyForm = this.ControlFactory.CreateForm();
            DMUniqueConstraintPropertySelectorControl uniqueConstraintPropertySelectorControl = new DMUniqueConstraintPropertySelectorControl(this.ControlFactory);
            uniqueConstraintPropertySelectorControl.BusinessObject = dmUniqueConstraint;
            _uniqueConstraintPropertyForm.Controls.Add(uniqueConstraintPropertySelectorControl);
            uniqueConstraintPropertySelectorControl.SaveClicked += ((sender, e) => _uniqueConstraintPropertyForm.Close());
            uniqueConstraintPropertySelectorControl.CloseClicked += ((sender, e) => _uniqueConstraintPropertyForm.Close());
            _uniqueConstraintPropertyForm.Width = 610;
            _uniqueConstraintPropertyForm.Height = 300;
            _uniqueConstraintPropertyForm.ShowDialog();
        }

        public DMUniqueConstraint SelectedUniqueConstraint
        {
            get { return (DMUniqueConstraint) GridControl.SelectedBusinessObject; }
            set { GridControl.SelectedBusinessObject = value; }
        }

        public DMClass Class
        {
            get { return _class; }
            set
            {
                _class = value;
                if (_class != null)
                {
                    this.Enabled = true;
                    GridControl.BusinessObjectCollection = _class.UniqueConstraints;
                }
                else
                {
                    
                    this.Enabled = false;
                    //This is done so that the grid is set up with the basic columns etc required for DMUniqueConstraint
                    GridControl.BusinessObjectCollection =  new BusinessObjectCollection<DMUniqueConstraint>();
                }
                EnableAddPropertiesButton();
            }
        }

        public BusinessObjectCollection<DMUniqueConstraint> UniqueConstraints
        {
            get { return (BusinessObjectCollection<DMUniqueConstraint>)GridControl.BusinessObjectCollection; }
        }

        private void FireUniqueConstraintSelected(DMUniqueConstraint DMUniqueConstraint)
        {
            if (this.UniqueConstraintSelected != null)
            {
                this.UniqueConstraintSelected(this, new BOEventArgs<DMUniqueConstraint>(DMUniqueConstraint));
            }
            if (this.BusinessObjectSelected != null)
            {
                this.BusinessObjectSelected(this, new BOEventArgs(DMUniqueConstraint));
            }
        }

        private void EnableAddPropertiesButton()
        {
            IButton addPropertyButton = this.GridControl.Buttons["AddProperties"];
            if (addPropertyButton == null)
            {
                const string message =
                    "The 'Add Properties' Button cannot be enabled or disabled since the 'Add Properties' button has been removed";
                throw new HabaneroDeveloperException(message, message);
            }
            addPropertyButton.Enabled = this.SelectedBusinessObject != null;
        }

        public void SetForm(IFormHabanero form)
        {
        }

        IBusinessObject IBusinessObjectControl.BusinessObject
        {
            get { return Class; }
            set { Class = (DMClass) value; }
        }

        #region IBOColSelector

        public event EventHandler<BOEventArgs> BusinessObjectSelected;

        public void Clear()
        {
            this.GridControl.Clear();
        }

        public IBusinessObject GetBusinessObjectAtRow(int row)
        {
            return this.GridControl.GetBusinessObjectAtRow(row);
        }

        public IBusinessObjectCollection BusinessObjectCollection
        {
             get { return this.GridControl.BusinessObjectCollection; }
             set { this.GridControl.BusinessObjectCollection = value; }
        }

        public IBusinessObject SelectedBusinessObject
        {
           get { return this.GridControl.SelectedBusinessObject; }
           set { this.GridControl.SelectedBusinessObject = value; }
        }

        public int NoOfItems
        {
            get { return this.GridControl.NoOfItems; }
        }

        /// <summary>
        ///             Gets and sets whether this selector autoselects the first item or not when a new collection is set.
        /// </summary>
        public bool AutoSelectFirstItem { get; set; }

        #endregion

 
 }
}